"use strict";

const fs = require("mz/fs");
const mkdir = require("mkdir-promise");
const path = require("path");
const pathExists = require("path-exists");

/**
 * File System helper.
 * @class FileService
 * @example
 * let fileService = new FileService();
 */
/*export*/ class FileService {
  /**
   * Constructor
   */
  constructor() {}

  /**
   * Concatenate a path
   * @access private
   * @param {string} name current path
   * @param {string} parent parent of path
   * @return {string} path ready to be created
   */
  concat(name, parent) {
    if (null != parent) {
      return path.join(parent, name);
    }
    return name;
  }

  /**
   * Create a path
   * @access private
   * @param {string} file path to create
   * @param {bool} [isRecursive=false] recursively create is true, false otherwise
   * @return {promise} path creation
   */
  create(file) {
    return mkdir(file);
  }

  /**
   * find or create path(s)
   * @param {object} payload
   * @return {promise} path creation
   */
  findOrCreate(payload) {
    let fileName;
    fileName = this.concat(payload.name,
                             payload.parent || null);
    return pathExists(fileName).then((exists) => {
      if (exists) {
        return true;
      }
      return this.create(fileName);
    });
  }
}
module.exports = FileService;
